import BaseClass from './BaseClass'

import Feature from 'ol/Feature'
import {Icon, Style} from 'ol/style'

export default class Dbmap extends BaseClass {
  constructor(mapid, option) {
    super(mapid, option)
    this.state = {}
  }

  /**
   * 关闭所有弹出层
   */
  closeAllOverLay() {
    let overLayList = this.map.getOverlays().getArray()
    overLayList.forEach((el) => {
      el.setPosition(undefined)
    })
  }

  /**
   * 删除所有弹出层
   * @returns {Array}
   */
  removeAllOverLay() {
    let overLayList = this.map.getOverlays().getArray()
    overLayList.forEach((el) => {
      this.map.removeOverlay(el)
    })
    return overLayList
  }

  /**
   * 删除弹出层
   * @param id 创建弹窗的id
   * @returns {any}
   */
  removeOverLayById(id) {
    let overlay = this.map.getOverlayById(id)
    this.map.removeOverlay(overlay)
    return overlay
  }

  /**
   * 创建一个弹窗
   * @param container
   * @param id
   * @param option
   * @returns {Overlay}
   */
  addOverLay(container, id, option = {}) {
    // 创建一个弹窗 Overlay 对象
    let overlay = this.createOverlay(container, {...option, id})
    // 将弹窗添加到 map 地图中
    this.map.addOverlay(overlay)
    return overlay
  }

  //获取弹窗
  getOverLay(id) {
    return this.map.getOverlayById(id)
  }

  //移动要素位置
  setFeatureLnglat(lng, lat, feature) {
    if (!feature) return
    let coordinate = this.transform(lng, lat)

    let geometry = feature.getGeometry()
    geometry.setCoordinates(coordinate)
  }

  setIconStyle(feature) {
    if (!feature) {
      return
    }
    let style = new Style({
      image: new Icon({
        src: feature.get('src')
      })
    })
    feature.setStyle(style)
  }

  /**
   * 经纬度序列化
   * @param {*} list
   * @param {*} type      // type = 1 返回格式为 {   "longitude": 103.98917318554687,"latitude": 31.147139915527344} type = 2 [103.86969686718751, 31.259749778808594]
   * @param {*} config     经纬度字段
   * @returns
   */
  lonlatFormat(list = [], type = 1, config) {
    let arr = []
    config = config || {
      lng: 'longitude',
      lat: 'latitude'
    }
    list.forEach((el) => {
      let item = null
      if (type === 1) {
        item = {
          [config.lng]: el[0], //经度
          [config.lat]: el[1] //纬度
        }
      } else {
        let lng = el[config.lng]
        let lat = el[config.lat]
        item = [lng, lat]
      }
      arr.push(item)
    })
    return arr
  }

  //经纬度转米(单位)
  degreesToMeter(radius) {
    let metersPerUnit = this.map.getView().getProjection().getMetersPerUnit()
    let circleRadius = radius * metersPerUnit
    return circleRadius
  }

  //米(单位)转经纬度
  meterToDegrees(circleRadius) {
    let metersPerUnit = this.map.getView().getProjection().getMetersPerUnit()
    let radius = circleRadius / metersPerUnit
    return radius
  }


  getInteraction(code) {
    let interactions = this.map.getInteractions().getArray()

    for (const item of interactions) {
      if (item.get('id') === code) {
        return item
      }
    }
  }

  //
}
